const { join } = require("path");
const { exec } = require("child_process");
const { readdir } = require("fs-extra");

const initExec = async (command, options = {}) => {
    return new Promise((resolve, reject) => {
        const root = process.cwd();
        const npmInstall = exec(command, { cwd: root, ...options })
        npmInstall.on('close', () => resolve())
        npmInstall.on('error', (e) => reject(e))
        npmInstall.stdout.pipe(process.stdout)
    })
}
async function updateProject() {
    const root = process.cwd();
    // install
    const { cpSync } = require('fs-extra')
    cpSync(join(__dirname, 'prisma/schema.prisma'), join(root, 'prisma/schema.prisma'))
    await initExec(`prisma db pull`)
    await initExec(`prisma generate`)
    await initExec('pnpm run zapatos')
    await initExec('pnpm run -r tsc')
    await initExec('pnpm run unocss:build')
    // install sql
    require('reflect-metadata')
    const { init, watchAddon } = require('@sker/core')
    await init()
    await initExec('pnpm run tsc', { cwd: join(root, 'addons/@imeepos/core') }).catch()
    await watchAddon('imeepos', 'core', false).catch()
    // 编译core模块
    const scopes = await readdir(join(root, 'addons'))
    // 一个一个来 防止cpu和内存承受不住
    await promiseAllSort(scopes.map(scope => {
        return async () => {
            if (scope.startsWith('@')) {
                const addons = await readdir(join(root, 'addons', scope))
                await promiseAllSort(addons.map(addon => {
                    return async () => {
                        try {
                            if (scope === '@imeepos' && addon === 'core') return;
                            if (addon.startsWith('.')) return;
                            // 编译模块
                            await initExec('pnpm run tsc', { cwd: join(root, 'addons', scope, addon) })
                            // 打包模块前端文件
                            await watchAddon(scope.replace('@', ''), addon, false)
                        } catch (e) {
                            console.log({ scope, addon })
                        }
                    }
                }))
            }
        }
    }))
    await initExec('pnpm run restart', { cwd: process.cwd() })
    console.log(`恭喜您，系统更新完成，请用命令pnpm run start/prod 启动 然后浏览器访问 http://0.0.0.0:3102`)
}
updateProject();

async function promiseAllSort(list) {
    const items = [...list];
    let item = items.pop()
    while (item) {
        await item()
        item = items.pop()
    }
}
